package cirno.open.api.service.impl;

import cirno.open.api.common.ErrorCode;
import cirno.open.api.constant.SignConstant;
import cirno.open.api.exception.BusinessException;
import cirno.open.api.model.entity.User;
import cirno.open.api.service.SignService;
import cirno.open.api.service.UserService;
import cirno.open.api.utils.SignUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@RequiredArgsConstructor
public class SignServiceImpl implements SignService {

    private final UserService userService;

    private final StringRedisTemplate redisTemplate;

    @Override
    public Map<String, String> genSign(String accessKey, String secretKey) {
        if (ObjectUtils.anyNull(accessKey, secretKey))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccessKey, accessKey);
        queryWrapper.eq(User::getSecretKey, secretKey);
        User user = userService.getOne(queryWrapper);
        if (user == null)
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        //获取签名如果签名没过期
        String sign = redisTemplate.opsForValue().get(SignConstant.SIGN_CACHE_KEY + user.getAccessKey());
        if (sign == null) {
            //生成签名
            sign = SignUtils.getSign(accessKey, secretKey);
        }
        //设置签名过期时间
        redisTemplate.opsForValue().set(SignConstant.SIGN_CACHE_KEY + user.getAccessKey(), sign, 1L, TimeUnit.HOURS);
        return Map.of("accessKey", accessKey, "sign", sign, "timestamp", String.valueOf(System.currentTimeMillis() / 1000));
    }
}
